import React, { memo, useState, useEffect, useRef } from 'react';
import { useSelector, useDispatch } from 'react-redux'
import { Message } from '@arco-design/web-react';

import { Carousel } from '@arco-design/web-react';

import { getSizeImage, getPlayUrl, getRandom } from '../../utils';
import { parseLyric } from '../../utils/parse-lyric';
import {
  getSongDetail,
  getLyric,
  getSongsTrancks,
  getSearchMusic,
} from './api';

import './index.css';
import { ImgRotat } from './style';

export default memo(function Music() {
  const dispatch = useDispatch()
  const audioRef = useRef();
  const [songs, setSongs] = useState([]);
  const [arName, setArName] = useState();
  const [musicURL, setMusicURL] = useState();
  const [isPlay, setIsPlay] = useState(false);
  const [lyricList = [], setlyricList] = useState();
  const [currentLyrics, setCurrentLyrics] = useState();
  const [trancks, setTrancks] = useState([]);
  const [currentIndex, setCurrentIndex] = useState(getRandom(30));
  const [isCircular, setIsCirular] = useState();
  const [trancksId, setTrancksId] = useState(3778678);
  const [searchResult = [], setSearchResult] = useState();

  const searchMusic = e => {
    getSearchMusic(e.target.value).then(res => {
      setSearchResult(res.data.result.songs);
    });
  };

  const musicItemClick = async item => {
    getSongDetail(item.id).then(res => {
      setSongs(res?.data?.songs[0]);
      setArName(res?.data?.songs[0].ar[0].name);
    });
    const musicUrl = await getPlayUrl(item.id);
    await getLyric(item.id).then(res => {
      let currentLyric = parseLyric(res.data.lrc.lyric);
      setlyricList(currentLyric);
    });
    setMusicURL(musicUrl);
    audioRef.current.play();
    setIsPlay(true);
  };

  const musicStyleId = useSelector(state => state.trancksId)
  const voiceSize = useSelector(state => state.voiceSize)
  const bannerStyle = useSelector(state => state.bannerStyle)

  useEffect(() => {
    setTrancksId(musicStyleId)
    audioRef.current.volume = voiceSize/100
    setIsCirular(bannerStyle)
  }, [musicStyleId,voiceSize,bannerStyle])

  async function fetchData() {
    let musicUrl;
    try {
      musicUrl = await getPlayUrl(trancks[currentIndex]?.id);
    } catch (err) {
      Message.err(err);
      next();
    }
    setMusicURL(musicUrl);
    trancks.length &&
      (await getLyric(trancks[currentIndex]?.id).then(res => {
        let currentLyric = parseLyric(res?.data?.lrc?.lyric);
        setlyricList(currentLyric);
      }));
    trancks.length &&
      getSongDetail(trancks[currentIndex]?.id).then(res => {
        setSongs(res?.data?.songs[0]);
        setArName(res?.data?.songs[0].ar[0].name);
      });
  }

  useEffect(() => {
    fetchData();
  }, [trancks]);

  useEffect(() => {
    getSongsTrancks(trancksId).then(res => {
      setTrancks(res?.data?.playlist?.trackIds);
    });
    trancks.length &&
      getSongDetail(trancks[currentIndex]?.id).then(res => {
        setSongs(res?.data?.songs[0]);
      });
  }, [currentIndex, trancksId]);

  const stop = async () => {
    const musicUrl = await getPlayUrl(songs?.id);
    await getLyric(songs?.id).then(res => {
      let currentLyric = parseLyric(res.data.lrc.lyric);
      setlyricList(currentLyric);
    });
    setMusicURL(musicUrl);
    if (!isPlay) {
      audioRef.current.play();
      setIsPlay(true);
    } else {
      audioRef.current.pause();
      setIsPlay(false);
    }
  };
  const next = () => {
    setCurrentIndex(getRandom(trancks.length - 1));
    setIsPlay(true);
  };
  const handleLyric = e => {
    const currentTime = e.target.currentTime;
    // 获取当前歌词
    let curruentLyricIndex = 0;
    for (let i = 0; i < lyricList.length; i++) {
      let lyricItem = lyricList[i];
      if (currentTime * 1000 < lyricItem.time) {
        curruentLyricIndex = i;
        break;
      }
    }
    let currentIndexL = curruentLyricIndex - 1;
    const content =
      lyricList[currentIndexL] && lyricList[currentIndexL].content;
    setCurrentLyrics(content);
  };
  return (
    <Carousel
      showArrow='hover'
      animation='fade'
      indicatorPosition='none'
      style={{
        width: '100%',
        height: 250,
        padding: 0,
      }}
    >
      <div className='flex-c wrap' style={{ padding: 0 }}>
        <div className='Img'>
          {trancks.length !== 0 ? (
            <ImgRotat
              src={getSizeImage(songs?.al?.picUrl, 100)}
              isPlay={isPlay}
              isCircular={isCircular}
              alt=''
            />
          ) : (
            <img src={require('../../assets/img/none.png')} alt='' />
          )}
          <span
            className={
              isCircular
                ? 'isCircular iconfont icon-xuanzhuan flex-c'
                : 'iconfont icon-xuanzhuan flex-c'
            }
            onClick={e => {dispatch({type:'bannerStyle',data:!isCircular})}}
          ></span>
        </div>
        <div className='songInfo'>
          <div className='name'>{songs?.name}</div>
          {trancks.length === 0 && <h2>暂无歌曲</h2>}
          <div className='artists'>{arName}</div>
          <div className='lyrcs'>
            {currentLyrics ? currentLyrics : '......'}
          </div>
          <div className='control'>
            <span onClick={next} className='iconfont icon-shangyiqu'></span>
            {isPlay ? (
              <span onClick={stop} className='iconfont icon-zanting'></span>
            ) : (
              <span onClick={stop} className='iconfont icon-kaishi'></span>
            )}

            <span
              onClick={next}
              className='iconfont icon-shangyiqu rotat'
            ></span>
          </div>
        </div>
        <audio
          ref={audioRef}
          autoPlay={true}
          src={musicURL}
          controls={false}
          onPlaying={() => setIsPlay(true)}
          onPause={() => setIsPlay(false)}
          onTimeUpdate={e => handleLyric(e)}
          onEnded={() => next()}
        ></audio>
      </div>
      <div className='flex-c'>
        <input
          className='input'
          type='text'
          placeholder='搜索音乐'
          onChange={e => searchMusic(e)}
        />
        <div className='songsList'>
          {searchResult.map((item, index) => {
            return (
              <div
                className='musicResult'
                key={item.id}
                onClick={e => musicItemClick(item)}
              >
                <span className='music-index text-nowrap'>{index + 1}</span>
                <span className='music-title text-nowrap'> {item.name}</span>
                <span className='music-name text-nowrap '>
                  {item.artists[0].name}
                </span>
              </div>
            );
          })}
        </div>
      </div>
    </Carousel>
  );
});
